package org.ofbiz.osgi.activator;

import java.util.Map;

import org.ofbiz.base.util.Debug;
import org.ofbiz.osgi.service.lookup.ServiceLookup;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceRegistration;

public class HostActivator implements BundleActivator, ServiceListener {
    
    public final static String module = HostActivator.class.getName();
    
    private Map<String, Object> lookupServiceMap;
    private BundleContext context;
    private ServiceRegistration serviceRegistration;
    
    public HostActivator(Map<String, Object> lookupServiceMap) {
        this.lookupServiceMap = lookupServiceMap;
    }
    
    @Override
    public void start(BundleContext context) throws Exception {
        this.context = context;
        this.context.addServiceListener(this);
        ServiceLookup serviceLookup = new ServiceLookup() {
            
            @Override
            public Object lookup(String serviceName) {
                return lookupServiceMap.get(serviceName);
            }
        };
        this.serviceRegistration = this.context.registerService(
                ServiceLookup.class.getName(), serviceLookup, null);
    }
    
    @Override
    public void stop(BundleContext context) throws Exception {
        this.serviceRegistration.unregister();
        this.context.removeServiceListener(this);
        this.context = null;
    }
    
    @Override
    public void serviceChanged(ServiceEvent event) {
        String[] objectClass = (String[]) event.getServiceReference()
                .getProperty("objectClass");
        
        if (event.getType() == ServiceEvent.REGISTERED) {
            Debug.logInfo("Service of type " + objectClass[0] + " registered.",
                    module);
        } else if (event.getType() == ServiceEvent.UNREGISTERING) {
            Debug.logInfo("Service of type " + objectClass[0]
                    + " unregistered.", module);
        } else if (event.getType() == ServiceEvent.MODIFIED) {
            Debug.logInfo("Service of type " + objectClass[0] + " modified.",
                    module);
        }
    }
    
    public Bundle[] getBundles() {
        if (this.context != null) {
            return this.context.getBundles();
        }
        return null;
    }
    
    public BundleContext getContext() {
        return this.context;
    }
}
